﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SpaceGame
{
    public class ConsoleRenderer : IRenderer    
    {
        private int matrixRows;
        private int matrixCols;
        private char[,] matrix;

        public ConsoleRenderer(int rows, int cols)
        {
            this.matrixRows = rows;
            this.matrixCols = cols;

            this.matrix = new char[rows, cols];

            this.ClearBuffer();
        }


        public void FlushBuffer()
        {
            Console.SetCursorPosition(0, 0);

            StringBuilder frame = new StringBuilder();

            for (int row = 0; row < this.matrixRows; row++)
            {
                for (int col = 0; col < this.matrixCols; col++)
                {
                    frame.Append(this.matrix[row, col]);
                }
            }

            Console.WriteLine(frame.ToString());
        }

        public void AddToBuffer(IRenderable obj)
        {
            int imageRows = obj.Image.GetLength(0);
            int imageCols = obj.Image.GetLength(1);

            for (int row = 0; row < imageRows; row++)
            {
                for (int col = 0; col < imageCols; col++)
                {
                    int y = obj.TopLeft.Row + row;
                    int x = obj.TopLeft.Col + col;

                    if(x < this.matrixCols && y < this.matrixRows)
                        this.matrix[y, x] = obj.Image[row, col];
                }
            }
        }

        public void ClearBuffer()
        {
            for (int row = 0; row < this.matrixRows; row++)
            {
                for (int col = 0; col < this.matrixCols; col++)
                {
                    this.matrix[row, col] = ' ';
                }
            }
        }
    }
}
